<template>
  <div class="inventory-container">
    <el-card class="search-card">
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="盘点单号" label-width="80px">
          <el-input v-model="searchForm.code" placeholder="请输入" clearable style="width: 160px" />
        </el-form-item>
        <el-form-item label="盘点结果" label-width="80px">
          <el-select v-model="searchForm.result" placeholder="请选择" clearable style="width: 160px">
            <el-option label="草稿" value="draft" />
            <el-option label="盘盈" value="surplus" />
            <el-option label="盘亏" value="loss" />
          </el-select>
        </el-form-item>
        <el-form-item label="盘点类型" label-width="80px">
          <el-select v-model="searchForm.type" placeholder="请选择" clearable style="width: 160px">
            <el-option label="全部盘点" value="all" />
            <el-option label="部分盘点" value="partial" />
          </el-select>
        </el-form-item>
        <el-form-item label="仓库名称" label-width="80px">
          <el-select v-model="searchForm.warehouse" placeholder="请选择" clearable style="width: 160px">
            <el-option label="仓库盛" value="warehouse1" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="handleReset">重置</el-button>
          <el-button type="success">高级搜索</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <el-card class="table-card">
      <div class="toolbar">
        <el-button type="success" @click="handleAdd">新增</el-button>
        <el-button type="danger" @click="handleBatchDelete">删除</el-button>
        <el-button @click="handleExport">导出</el-button>
        <el-button @click="handlePrint">作废</el-button>
        <el-button @click="handleGenerateWarehouse">锁定仓库</el-button>
        <el-button @click="handleRefresh">刷新</el-button>
      </div>

      <el-table :data="tableData" style="width: 100%" stripe border size="default" v-loading="loading"
        @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" />
        <el-table-column label="#" width="60" align="center">
          <template #header>
            <el-icon style="cursor: pointer; font-size: 16px; color: #409eff" @click="handleOpenHeaderSettings">
              <Setting />
            </el-icon>
          </template>
          <template #default="{ $index }">
            {{ $index + 1 }}
          </template>
        </el-table-column>
        <!-- 动态列：根据配置显示/隐藏和排序 -->
        <template v-for="col in currentHeaderConfig.filter(c => c.visible)" :key="col.key">
          <!-- 盘点单号 -->
          <el-table-column v-if="col.key === 'code'" prop="code" label="盘点单号" :width="col.width" show-overflow-tooltip>
            <template #default="{ row }">
              <span :style="{ color: row.color || '#333' }">{{ row.code }}</span>
            </template>
          </el-table-column>
          <!-- 盘点结果 -->
          <el-table-column v-else-if="col.key === 'result'" prop="result" label="盘点结果" :width="col.width"
            align="center">
            <template #default="{ row }">
              <el-tag :type="getResultTagType(row.result)" size="small">
                {{ row.result }}
              </el-tag>
            </template>
          </el-table-column>
          <!-- 仓库名称 -->
          <el-table-column v-else-if="col.key === 'warehouseName'" prop="warehouseName" label="仓库名称" :width="col.width"
            show-overflow-tooltip />
          <!-- 盘点类型 -->
          <el-table-column v-else-if="col.key === 'inventoryTypeName'" prop="inventoryTypeName" label="盘点类型"
            :width="col.width" align="center" />
          <!-- 盘点开始时间 -->
          <el-table-column v-else-if="col.key === 'startTime'" prop="startTime" label="盘点开始时间" :width="col.width" />
          <!-- 盘点结束时间 -->
          <el-table-column v-else-if="col.key === 'endTime'" prop="endTime" label="盘点结束时间" :width="col.width" />
          <!-- 盘点货品 -->
          <el-table-column v-else-if="col.key === 'productNames'" prop="productNames" label="盘点货品" :width="col.width"
            show-overflow-tooltip>
            <template #default="{ row }">
              <span>{{ row.productNames || '-' }}</span>
            </template>
          </el-table-column>
          <!-- 盘点数量 -->
          <el-table-column v-else-if="col.key === 'quantity'" prop="quantity" label="盘点数量" :width="col.width"
            align="center">
            <template #default="{ row }">
              <span>{{ row.quantity || 0 }}</span>
            </template>
          </el-table-column>
          <!-- 盘盈数量 -->
          <el-table-column v-else-if="col.key === 'surplusQuantity'" prop="surplusQuantity" label="盘盈数量"
            :width="col.width" align="center">
            <template #default="{ row }">
              <span style="color: #67c23a; font-weight: 500">{{ row.surplusQuantity || 0 }}</span>
            </template>
          </el-table-column>
          <!-- 盘盈金额 -->
          <el-table-column v-else-if="col.key === 'totalAmount'" prop="totalAmount" label="盘盈金额" :width="col.width"
            align="right">
            <template #default="{ row }">
              <span style="color: #67c23a; font-weight: 500">¥{{ row.totalAmount || '0.00' }}</span>
            </template>
          </el-table-column>
          <!-- 盘亏金额 -->
          <el-table-column v-else-if="col.key === 'lossAmount'" prop="lossAmount" label="盘亏金额" :width="col.width"
            align="right">
            <template #default="{ row }">
              <span style="color: #f56c6c; font-weight: 500">¥{{ row.lossAmount || '0.00' }}</span>
            </template>
          </el-table-column>
          <!-- 经办人 -->
          <el-table-column v-else-if="col.key === 'operator'" prop="operator" label="经办人" :width="col.width" />
          <!-- 制单人 -->
          <el-table-column v-else-if="col.key === 'creator'" prop="creator" label="制单人" :width="col.width" />
          <!-- 所在部门 -->
          <el-table-column v-else-if="col.key === 'department'" prop="department" label="所在部门" :width="col.width"
            show-overflow-tooltip />
          <!-- 制单时间 -->
          <el-table-column v-else-if="col.key === 'createTime'" prop="createTime" label="制单时间" :width="col.width" />
        </template>
        <el-table-column label="操作" width="150" fixed="right">
          <template #default="{ row }">
            <el-button link type="primary" size="small" @click="handleEdit(row)">
              编辑
            </el-button>
            <el-button link type="danger" size="small" @click="handleDelete(row)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 表头设置对话框 -->
      <el-dialog v-model="headerSettingsVisible" title="表头设置" width="600px" :close-on-click-modal="false">
        <div class="header-settings-tip">
          表头不得少于5项,最多支持30项
        </div>
        <el-table :data="headerSettingsList" border stripe style="width: 100%" row-key="key"
          class="header-settings-table">
          <el-table-column prop="visible" label="显示" width="80" align="center">
            <template #default="{ row }">
              <el-checkbox v-model="row.visible" :disabled="!row.canHide" />
            </template>
          </el-table-column>
          <el-table-column prop="label" label="表头名称" />
          <el-table-column label="拖动排序" width="100" align="center">
            <template #default>
              <el-icon class="sortable-handle" style="font-size: 18px; color: #909399">
                <Rank />
              </el-icon>
            </template>
          </el-table-column>
        </el-table>
        <template #footer>
          <div class="dialog-footer">
            <el-button text type="primary" @click="handleResetHeaderSettings">恢复默认</el-button>
            <el-button @click="handleCloseHeaderSettings">取消</el-button>
            <el-button type="primary" @click="handleConfirmHeaderSettings">确定</el-button>
          </div>
        </template>
      </el-dialog>

      <div class="pagination">
        <span class="total">总 {{ total }} 条</span>
        <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :page-sizes="[10, 20, 50, 100]"
          layout="prev, pager, next, sizes" :total="total" @size-change="handleSizeChange"
          @current-change="handleCurrentChange" />
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, watch, nextTick, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Setting, Rank } from '@element-plus/icons-vue'
import Sortable from 'sortablejs'
import { queryInventoryList } from '@/api/inventory'

const router = useRouter()

// 后端返回的数据结构
interface BackendInventoryItem {
  inventoryId: number
  inventoryCode: string
  warehouseId: number
  inventoryTypeName: string
  warehouseName: string
  handlerrId: number
  handlerName: string
  warehouseDeptId: number
  warehouseDeptName: string
  inventoryDateTime: string
  inventoryEndTime: string
  inventoryContent: string
  inventoryQuantity: string
  surplusQuantity: string
  inventoryShortageQuantity: string
  surplusAmount: string
  inventoryLossAmount: string
  dataStatus: number
  createName: string
  createTime: string
  productNames: string
  attachmentCount: number
  isDeleted: boolean
}

// 前端显示的表格数据
interface InventoryItem {
  code: string
  result: string
  warehouseName: string
  startTime: string
  endTime: string
  inventoryTypeName: string
  outboundStatus: string
  inboundStatus: string
  productNames: string
  quantity: number
  surplusQuantity: number
  totalAmount: string
  lossAmount: string
  operator: string
  creator: string
  department: string
  createTime: string
  color?: string
}

const searchForm = reactive({
  code: '',
  result: '',
  type: '',
  warehouse: ''
})

const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const loading = ref(false)

const tableData = ref<InventoryItem[]>([])

const selectedRows = ref<InventoryItem[]>([])

// 转换后端数据为前端显示格式
const transformBackendData = (backendData: BackendInventoryItem[]): InventoryItem[] => {
  return backendData.map(item => {
    // 计算盘点结果：先判断 dataStatus，再判断 inventoryShortageQuantity
    let result = '无盈亏'
    if (item.dataStatus === 1) {
      result = '草稿'
    } else if (Number(item.inventoryShortageQuantity) > 0) {
      result = '有盈亏'
    } else {
      result = '无盈亏'
    }

    // 格式化时间
    const formatDateTime = (dateTimeStr: string) => {
      if (!dateTimeStr) return ''
      const date = new Date(dateTimeStr)
      const year = date.getFullYear()
      const month = String(date.getMonth() + 1).padStart(2, '0')
      const day = String(date.getDate()).padStart(2, '0')
      const hours = String(date.getHours()).padStart(2, '0')
      const minutes = String(date.getMinutes()).padStart(2, '0')
      const seconds = String(date.getSeconds()).padStart(2, '0')
      return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
    }

    return {
      code: item.inventoryCode || '',
      result: result,
      warehouseName: item.warehouseName || '',
      inventoryTypeName: item.inventoryTypeName || '',
      startTime: formatDateTime(item.inventoryDateTime),
      endTime: formatDateTime(item.inventoryEndTime),
      outboundStatus: '', // 已删除
      inboundStatus: '', // 已删除
      productNames: item.productNames || '',
      quantity: Number(item.inventoryQuantity) || 0,
      surplusQuantity: Number(item.surplusQuantity) || 0,
      totalAmount: item.surplusAmount || '0.00',
      lossAmount: item.inventoryLossAmount || '0.00',
      operator: item.handlerName || '',
      creator: item.createName || '',
      department: item.warehouseDeptName || '',
      createTime: formatDateTime(item.createTime)
    }
  })
}

// 获取盘点列表数据
const fetchInventoryList = async () => {
  loading.value = true
  try {
    const params: any = {
      'QueryDTO.PageIndex': currentPage.value,
      'QueryDTO.PageSize': pageSize.value
    }

    // 添加搜索条件
    if (searchForm.code) {
      params['QueryDTO.InventoryCode'] = searchForm.code
    }
    if (searchForm.result) {
      params['QueryDTO.DataStatus'] = searchForm.result
    }
    if (searchForm.warehouse) {
      params['QueryDTO.WarehouseName'] = searchForm.warehouse
    }

    const response = await queryInventoryList(params)

    if (response.code === 200 && response.data) {
      tableData.value = transformBackendData(response.data.data || [])
      total.value = response.data.totalCount || 0
    } else {
      ElMessage.error(response.message || '查询失败')
      tableData.value = []
      total.value = 0
    }
  } catch (error: any) {
    console.error('查询盘点列表失败:', error)
    ElMessage.error(error.message || '查询失败，请稍后重试')
    tableData.value = []
    total.value = 0
  } finally {
    loading.value = false
  }
}

// 页面加载时获取数据
onMounted(() => {
  fetchInventoryList()
})

const handleSearch = () => {
  currentPage.value = 1 // 重置到第一页
  fetchInventoryList()
}

const handleReset = () => {
  Object.assign(searchForm, {
    code: '',
    result: '',
    type: '',
    warehouse: ''
  })
  currentPage.value = 1
  fetchInventoryList()
}

const handleAdd = () => {
  router.push('/warehouse/inventory/add')
}

const handleEdit = (row: InventoryItem) => {
  router.push({
    path: '/warehouse/inventory/add',
    query: { code: row.code, mode: 'edit' }
  })
}

const handleDelete = (row: InventoryItem) => {
  ElMessageBox.confirm(`确定要删除 ${row.code} 吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    ElMessage.success('删除成功')
  })
}

const handleBatchDelete = () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning('请选择要删除的数据')
    return
  }
  ElMessageBox.confirm(`确定要删除选中的 ${selectedRows.value.length} 条数据吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    ElMessage.success('删除成功')
  })
}

const handleExport = () => {
  ElMessage.info('导出数据')
}

const handlePrint = () => {
  ElMessage.info('作废')
}

const handleGenerateWarehouse = () => {
  ElMessage.info('锁定仓库')
}

const handleRefresh = () => {
  fetchInventoryList()
}

const handleSelectionChange = (rows: InventoryItem[]) => {
  selectedRows.value = rows
}

const handleSizeChange = (val: number) => {
  pageSize.value = val
  currentPage.value = 1
  fetchInventoryList()
}

const handleCurrentChange = (val: number) => {
  currentPage.value = val
  fetchInventoryList()
}

// 获取盘点结果的标签类型
const getResultTagType = (result: string) => {
  if (result === '草稿') return 'info'
  if (result === '有盈亏') return 'warning'
  if (result === '无盈亏') return 'success'
  return ''
}

// ==================== 表头设置相关 ====================
interface HeaderConfig {
  key: string
  label: string
  visible: boolean
  canHide: boolean  // 是否可以隐藏（如序号、操作列不能隐藏）
  width?: number
  align?: string
  prop?: string
  fixed?: string
}

// 默认表头配置（按顺序）
const defaultHeaderConfig: HeaderConfig[] = [
  { key: 'code', label: '盘点单号', visible: true, canHide: true, width: 130, prop: 'code' },
  { key: 'result', label: '盘点结果', visible: true, canHide: true, width: 100, prop: 'result' },
  { key: 'warehouseName', label: '仓库名称', visible: true, canHide: true, width: 120, prop: 'warehouseName' },
  { key: 'inventoryTypeName', label: '盘点类型', visible: true, canHide: true, width: 100, prop: 'inventoryTypeName' },
  { key: 'startTime', label: '盘点开始时间', visible: true, canHide: true, width: 160, prop: 'startTime' },
  { key: 'endTime', label: '盘点结束时间', visible: true, canHide: true, width: 160, prop: 'endTime' },
  { key: 'productNames', label: '盘点货品', visible: true, canHide: true, width: 180, prop: 'productNames' },
  { key: 'quantity', label: '盘点数量', visible: true, canHide: true, width: 100, prop: 'quantity' },
  { key: 'surplusQuantity', label: '盘盈数量', visible: true, canHide: true, width: 100, prop: 'surplusQuantity' },
  { key: 'totalAmount', label: '盘盈金额', visible: true, canHide: true, width: 120, prop: 'totalAmount' },
  { key: 'lossAmount', label: '盘亏金额', visible: true, canHide: true, width: 120, prop: 'lossAmount' },
  { key: 'operator', label: '经办人', visible: true, canHide: true, width: 100, prop: 'operator' },
  { key: 'creator', label: '制单人', visible: true, canHide: true, width: 100, prop: 'creator' },
  { key: 'department', label: '所在部门', visible: true, canHide: true, width: 120, prop: 'department' },
  { key: 'createTime', label: '制单时间', visible: true, canHide: true, width: 160, prop: 'createTime' }
]

// 从localStorage加载表头设置
const loadHeaderSettings = (): HeaderConfig[] => {
  try {
    const saved = localStorage.getItem('inventory_header_settings')
    if (saved) {
      const parsed = JSON.parse(saved)
      // 合并默认配置，确保新增的列也被包含
      return defaultHeaderConfig.map(defaultCol => {
        const savedCol = parsed.find((col: HeaderConfig) => col.key === defaultCol.key)
        return savedCol ? { ...defaultCol, ...savedCol } : defaultCol
      })
    }
  } catch (error) {
    console.error('加载表头设置失败:', error)
  }
  return [...defaultHeaderConfig]
}

// 保存表头设置到localStorage
const saveHeaderSettings = (settings: HeaderConfig[]) => {
  try {
    localStorage.setItem('inventory_header_settings', JSON.stringify(settings))
  } catch (error) {
    console.error('保存表头设置失败:', error)
  }
}

// 当前表头配置
const currentHeaderConfig = ref<HeaderConfig[]>(loadHeaderSettings())
const headerSettingsVisible = ref(false)
const headerSettingsList = ref<HeaderConfig[]>([])
let sortableInstance: Sortable | null = null

// 打开表头设置对话框
const handleOpenHeaderSettings = () => {
  // 复制当前配置作为临时配置
  headerSettingsList.value = currentHeaderConfig.value.map(col => ({ ...col }))
  headerSettingsVisible.value = true

  // 等待DOM更新后初始化拖拽
  nextTick(() => {
    initSortable()
  })
}

// 初始化拖拽排序
const initSortable = () => {
  // 先销毁旧的实例
  if (sortableInstance) {
    sortableInstance.destroy()
    sortableInstance = null
  }

  // 等待DOM渲染完成
  setTimeout(() => {
    const tbody = document.querySelector('.header-settings-table .el-table__body-wrapper tbody')
    if (tbody) {
      sortableInstance = Sortable.create(tbody as HTMLElement, {
        handle: '.sortable-handle',
        animation: 150,
        ghostClass: 'sortable-ghost',
        onEnd: (evt: any) => {
          const { oldIndex, newIndex } = evt
          if (oldIndex !== undefined && newIndex !== undefined && oldIndex !== newIndex) {
            const movedItem = headerSettingsList.value.splice(oldIndex, 1)[0]
            headerSettingsList.value.splice(newIndex, 0, movedItem)
          }
        }
      })
    }
  }, 200)
}

// 关闭表头设置对话框
const handleCloseHeaderSettings = () => {
  headerSettingsVisible.value = false
  if (sortableInstance) {
    sortableInstance.destroy()
    sortableInstance = null
  }
}

// 恢复默认设置
const handleResetHeaderSettings = () => {
  headerSettingsList.value = defaultHeaderConfig.map(col => ({ ...col }))
  ElMessage.success('已恢复默认设置')
}

// 确认表头设置
const handleConfirmHeaderSettings = () => {
  // 检查显示的列数
  const visibleCount = headerSettingsList.value.filter(col => col.visible).length
  if (visibleCount < 5) {
    ElMessage.warning('表头不得少于5项')
    return
  }
  if (visibleCount > 30) {
    ElMessage.warning('表头最多支持30项')
    return
  }

  // 保存设置
  currentHeaderConfig.value = headerSettingsList.value
  saveHeaderSettings(currentHeaderConfig.value)

  ElMessage.success('表头设置已保存')
  handleCloseHeaderSettings()
}
</script>

<style scoped>
.inventory-container {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.search-card {
  margin-bottom: 0;
}

.search-card :deep(.el-card__body) {
  padding: 16px 20px;
}

.search-form {
  margin-bottom: 0;
}

.search-form :deep(.el-form-item) {
  margin-bottom: 12px;
  margin-right: 12px;
}

.search-form :deep(.el-form-item__label) {
  font-size: 14px;
  color: #606266;
}

.table-card {
  margin-bottom: 0;
}

.table-card :deep(.el-card__body) {
  padding: 16px 20px;
}

.toolbar {
  margin-bottom: 12px;
  display: flex;
  gap: 8px;
  flex-wrap: wrap;
}

.toolbar :deep(.el-button) {
  padding: 8px 15px;
}

.pagination {
  margin-top: 16px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.total {
  font-size: 14px;
  color: #606266;
}

/* 表头背景色 - 浅灰色突出层次 */
:deep(.el-table__header-wrapper) {
  background-color: #f5f7fa;
}

:deep(.el-table__header th) {
  background-color: #f5f7fa !important;
  color: #606266;
  font-weight: 600;
}

:deep(.el-table__header th .cell) {
  color: #606266;
  font-weight: 600;
}

/* 表头设置对话框样式 */
.header-settings-tip {
  margin-bottom: 12px;
  padding: 8px 12px;
  background-color: #f0f9ff;
  border-left: 4px solid #409eff;
  color: #606266;
  font-size: 13px;
}

.header-settings-table :deep(.el-table__body-wrapper) {
  max-height: 400px;
  overflow-y: auto;
}

.header-settings-table :deep(.sortable-handle) {
  cursor: move;
}

.dialog-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style>